﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using System.Net;

namespace smart_test
{
    public partial class ViewFrm : Form
    {
        delegate void NoArgumentDelegate();
        private string deepZoomUrl;

        public ViewFrm(string deepZoomUrl)
        {
            this.deepZoomUrl = deepZoomUrl;

            InitializeComponent();

            Load += new EventHandler(ViewFrm_Load);
            Closed += new EventHandler(ViewFrm_Closed);
        }

        void ViewFrm_Closed(object sender, EventArgs e)
        {
            deepZoomViewerControl1.Cleanup();
        }

        void ViewFrm_Load(object sender, EventArgs e)
        {
            deepZoomViewerControl1.ThumbnailLoaded += new EventHandler(deepZoomViewerControl1_ThumbnailLoaded);

            //deepZoomViewerControl1.ImageSelected += new EventHandler<SSM.DeepZoomViewer.ImageSelectedEventArgs>(deepZoomViewerControl1_ImageSelected);

            deepZoomViewerControl1.DeepZoomUrl
                = this.deepZoomUrl;

            pbPreview.Click += new EventHandler(pbPreview_Click);
        }

        private bool isDownloading;
        private IAsyncResult result;
        private HttpWebRequest httpWebRequest;
        private HttpWebResponse httpWebResponse;
        private Stream responseStream;

        private void RespCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                isDownloading = true;

                // State of request is asynchronous.
                httpWebResponse =
                    (HttpWebResponse)httpWebRequest.EndGetResponse(asynchronousResult);

                // Read the response into a Stream object.
                responseStream = httpWebResponse.GetResponseStream();

                // Cross thread 문제를 해결하기 위해 사용
                this.Invoke(
                    new NoArgumentDelegate(
                        ImageSetting
                    )
                );

                isDownloading = false;
            }
            catch (WebException e)
            {
                if (responseStream != null)
                    responseStream.Close();

                if (httpWebResponse != null)
                    httpWebResponse.Close();
            }
        }

        void ImageSetting()
        {
            try
            {
                pbPreview.Image = new Bitmap(responseStream);
            }
            catch (Exception ex) { }
        }

        void pbPreview_Click(object sender, EventArgs e)
        {
            pbPreview.Visible = false;

            if (isDownloading)
            {
                if (responseStream != null)
                    responseStream.Close();

                if (httpWebResponse != null)
                    httpWebResponse.Close();

                isDownloading = false;
            }
        }

        void deepZoomViewerControl1_ImageSelected(object sender, SSM.DeepZoomViewer.ImageSelectedEventArgs e)
        {
            if (isDownloading)
            {
                isDownloading = false;

                if (responseStream != null)
                    responseStream.Close();

                if (httpWebResponse != null)
                    httpWebResponse.Close();
            }

            if (!pbPreview.Visible)
                pbPreview.Visible = true;

            httpWebRequest =
                (HttpWebRequest)HttpWebRequest.Create(
                    new Uri(e.ImageUrl)
                );

            httpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), null);
        }

        void deepZoomViewerControl1_ThumbnailLoaded(object sender, EventArgs e)
        {
            deepZoomMonitor1.Image = deepZoomViewerControl1.Thumbnail;
        }

        void deepZoomViewerControl1_ViewportChanged(object sender, EventArgs e)
        {
            deepZoomMonitor1.ViewportX = deepZoomViewerControl1.SrcRect.Left;
            deepZoomMonitor1.ViewportY = deepZoomViewerControl1.SrcRect.Top;
            deepZoomMonitor1.MonitorWidth = deepZoomViewerControl1.SrcRect.Width;
            deepZoomMonitor1.MonitorHeight = deepZoomViewerControl1.SrcRect.Height;
        }

        private void btZoomIn_Click(object sender, EventArgs e)
        {
            if (deepZoomViewerControl1.CurrentLevel < 13)
            {
                deepZoomViewerControl1.MoveToLevel(deepZoomViewerControl1.CurrentLevel + 1);
            }
        }

        private void btZoomOut_Click(object sender, EventArgs e)
        {
            if (deepZoomViewerControl1.CurrentLevel > 8)
            {
                deepZoomViewerControl1.MoveToLevel(deepZoomViewerControl1.CurrentLevel - 1);
            }
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("저장 하시겠습니까?", " Content Save", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

            if (result == DialogResult.Yes)
            {
                if (!Directory.Exists(SmartMosaicClientConstants.SAVE_DIRECTORY))
                {
                    Directory.CreateDirectory(SmartMosaicClientConstants.SAVE_DIRECTORY);
                }

                // 파일이 없으면 파일 생성
                if (!File.Exists(SmartMosaicClientConstants.SAVE_FILE_PATH))
                {
                    File.Create(SmartMosaicClientConstants.SAVE_FILE_PATH).Close();
                }

                StreamWriter writer =
                    File.AppendText(SmartMosaicClientConstants.SAVE_FILE_PATH);

                string thumbnailFilePath = SmartMosaicClientConstants.SAVE_DIRECTORY
                    + "\\" + deepZoomViewerControl1.SessionID + ".jpg";

                string deepZoomUrl =
                    deepZoomViewerControl1.DeepZoomUrl;

                writer.Write(thumbnailFilePath + " " + deepZoomUrl + "\n");

                writer.Dispose();
                writer.Close();

                deepZoomViewerControl1.Thumbnail.Save(thumbnailFilePath, ImageFormat.Jpeg);

                MessageBox.Show("저장 완료.");
            }
            else
            {
                return;
            }
        }

        private void btClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btZoomIn_MouseDown(object sender, MouseEventArgs e)
        {
            btZoomInPress.Visible = true;
        }

        private void btZoomIn_MouseUp(object sender, MouseEventArgs e)
        {
            btZoomInPress.Visible = false;
        }

        private void btZoomOut_MouseDown(object sender, MouseEventArgs e)
        {
            btZoomOutPress.Visible = true;
        }

        private void btZoomOut_MouseUp(object sender, MouseEventArgs e)
        {
            btZoomOutPress.Visible = false;
        }

        private void btSave_MouseDown(object sender, MouseEventArgs e)
        {
            btSavePress.Visible = true;
        }

        private void btSave_MouseUp(object sender, MouseEventArgs e)
        {
            btSavePress.Visible = false;
        }

        private void btClose_MouseUp(object sender, MouseEventArgs e)
        {
            btClosePress.Visible = false;
        }

        private void btClose_MouseDown(object sender, MouseEventArgs e)
        {
            btClosePress.Visible = true;
        }
    }
}